<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 栅格布局 每一行col总共24份 当前占8份  gutter每一格中间的空隙 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <!-- 一个输入框  clear清空触发事件 -->
            <el-input @clear="init" clearable v-model="gettableinfo.query" placeholder="请输入内容" class="input-with">
              <!-- slot="append" 尾部的插槽 -->
              <el-button @click="init" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-col>
        <!-- 当前栅格占4 -->
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button @click="adduser_dialog = true" type="primary">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 表格 tableData 绑定的数据对象 边框 stripe隔行变色-->
      <el-table :data="tableData" :border="true" stripe style="width: 100%">
        <!-- 每一行 index表示当前行是索引-->
        <el-table-column label="#" type="index"></el-table-column>
        <!-- prop="username" 这个属性表示表格内容采用table的 :data对象内的对应属性-->
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 自定义表格内容 插槽 插槽传入的数据在scope.row内-->
          <template slot-scope="scope">
            <!-- 开关触发事件 change -->
            <el-switch @change="switch_value(scope.row)" v-model="scope.row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- eslint-disable-next-line  去除报错-->
          <template slot-scope="scope">
            <el-button @click="setitem(scope.row)" size="mini" type="primary" icon="el-icon-edit"></el-button>
            <el-button @click="deleteitem(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
            <!-- 
              tooltip 文字提示 enterable鼠标不能进入到提示区域
              effect 主题 content文字内容  placement悬浮提示到哪
            -->
            <el-tooltip :enterable="false" class="item" effect="dark" content="分配权限" placement="top">
              <el-button @click="allot(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页  
      size-change 页面条数改变的触发事件
      current-change 当前页改变触发 1 2 5..
      current-page 当前页数
      page-sizes 页码选择器选项
      page-size 每页显示多少条
      layout 各种拓展工具
      total 数据总数
      -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="gettableinfo.pagenum" :page-sizes="[2, 5, 10]" :page-size="gettableinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 修改 -->
    <!-- 弹窗  title标题 close弹框消失事件 visible.sync 控制弹窗展示的变量-->
    <el-dialog title="收货地址" @close="set_close" :visible.sync="setuser_dialog">
      <!-- 
        form表单 
        ref绑定方便操作表单的内置事件 
        label-width 表单左边的文本占多宽
        model 给表单绑定了数据对象
        rules 给表单绑定了校验对象
        -->
      <el-form ref="set_ref" label-width="70px" :model="setuser_form" :rules="setuser_rules">
        <!-- label 表单左侧的文字信息   prop是绑定了表单校验对象的哪一个属性-->
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model="setuser_form.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="setuser_form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="setuser_form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 插槽 footer 弹窗尾部-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="setuser_dialog = false">取 消</el-button>
        <el-button type="primary" @click="set_ok()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" @close="add_close" :visible.sync="adduser_dialog" width="50%">
      <el-form ref="add_ref" :model="adduser_from" :rules="adduser_rules">
        <el-form-item label="用户名" prop="username" label-width="70px">
          <el-input v-model="adduser_from.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="70px">
          <el-input v-model="adduser_from.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="70px">
          <el-input v-model="adduser_from.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile" label-width="70px">
          <el-input v-model="adduser_from.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adduser_dialog = false">取 消</el-button>
        <el-button type="primary" @click="adduser_fun">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 权限分配 -->
    <el-dialog title="添加用户" @close="allot_close" :visible.sync="allot_dialog" width="40%">
      <el-form ref="allot_ref" label-width="80px" :model="allot_from">
        <el-form-item label="当前用户 :" prop="username">
          {{ allot_from.username }}
        </el-form-item>
        <el-form-item label="当前角色 :" prop="rid">
          {{ allot_from.role_name }}
        </el-form-item>
        <el-form-item label="分配角色 :" prop="newrole_id">
          <el-select v-model="allot_from.newrole_id" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="allot_dialog = false">取 消</el-button>
        <el-button type="primary" @click="allot_fun">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //自定义校验表单
    let checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'));
      }
      if (value.indexOf('@') == -1) {
        callback(new Error('请输入正确的邮箱'));
      } else {
        callback();
      }
    };
    return {
      gettableinfo: {
        pagenum: 1,
        pagesize: 10,
        query: '',
      },
      total: 0,
      tableData: [],
      tableDataitem: ['#', '姓名', '邮箱', '电话', '角色', '状态', '操作'],
      setuser_dialog: false,
      adduser_dialog: false,
      setuser_form: {
        username: '',
        email: '',
        mobile: ''
      },
      setuser_rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
      },
      adduser_from: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      adduser_rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      setflg: {},
      allot_dialog: false,//分配权限窗口
      allot_from: {
        username: '',
        id: '',
        rid: '',
        ridname: '',
        newrole_id: ''
      },
      //select数据
      options: [],
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      //获取列表数据
      let { data: res } = await this.$http.get("users", { params: this.gettableinfo });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.tableData = res.data.users;
      this.total = res.data.total
    },
    handleSizeChange(val) {
      this.gettableinfo.pagesize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.gettableinfo.pagenum = val;
      this.init()
    },
    async switch_value(v) {
      let { data: res } = await this.$http.put(`users/${v.id}/state/${v.mg_state}`);
      if (res.meta.status !== 200) {
        v.mg_state = !v.mg_state
        return this.$message.error(res.meta.msg);
      }
    },
    adduser_fun() {
      this.$refs.add_ref.validate(async v => {
        if (!v) return this.$message.error('表单校验错误');
        let { data: res } = await this.$http.post("users", this.adduser_from);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.adduser_dialog = false
      })
    },
    add_close() {
      this.$refs.add_ref.resetFields();
    },
    //点击修改
    async setitem(row) {
      this.setuser_dialog = true;
      //获取列表数据 根据id
      let id = row.id;
      let { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.setuser_form = res.data
    },
    //关闭修改框
    set_close() {
      this.$refs.set_ref.resetFields();
      this.init();
    },
    //确定按钮
    async set_ok() {
      this.$refs.set_ref.validate(async v => {
        if (!v) return this.$message.error('表单校验错误');
        let { data: res } = await this.$http.put(`users/${this.setuser_form.id}`, { email: this.setuser_form.email, mobile: this.setuser_form.mobile });
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.setuser_dialog = false;
      })
    },
    //删除一个数据
    deleteitem(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //删除操作
        let { data: res } = await this.$http.delete(`users/${id}`);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.init();
        this.$message.success('删除成功');
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
    //分配按钮
    async allot(row) {
      this.allot_from = row;
      let { data: res } = await this.$http.get(`roles`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.options = res.data.map((v, i, arr) => {
        return {
          value: v.id,
          label: v.roleName,
        };
      });
      this.allot_dialog = true;
    },
    //弹框消失
    allot_close() {
      this.$refs.allot_ref.resetFields();
      this.allot_from.id = '';
    },
    //分配确定
    async allot_fun() {
      if (!this.allot_from.newrole_id) return this.$message.error('请分配角色')
      let { data: res } = await this.$http.put(`users/${this.allot_from.id}/role`, { rid: this.allot_from.newrole_id });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success('修改成功');
      this.init();
      this.allot_dialog = false;
    },
  }
}
</script>
<style lang="scss" scoped>
</style>